var util = require('../../utils/util.js');
var api = require('../../config/api.js');

var app = getApp();

Page({
  data: {
    cartGoods: [],
    cartTotal: 0,
    isEditCart: false,
    checkedAllStatus: true,
    editCartList: [],
    loadmoreText: '正在加载更多数据',
    nomoreText: '全部加载完成',
    totalPages: 1,
    page: 1
  },
  onLoad: function(options) {
    var that = this;
    // 页面初始化 options为页面跳转所带来的参数

    // this.getCartList();
    
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          scrollHeight: res.windowHeight
        });
      }
    });

  },
  onReady: function() {
    // 页面渲染完成

  },
  onShow: function() {
    // 页面显示
    this.getCartList();
  },
  onHide: function() {
    // 页面隐藏

  },
  onUnload: function() {
    // 页面关闭

  },

  onPullDownRefresh: function() {
    wx.stopPullDownRefresh();
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.getCartList()
  },

  getCartList: function() {
    let that = this;

    if (that.data.totalPages <= that.data.page - 1) {
      that.setData({
        nomore: true
      })
      return;
    }

    util.request(api.CartList, {
      username: app.globalData.userInfo.userName,
      page: that.data.page,
    }, 'POST').then(function(res) {
      console.log(res);
      if (res.status === 1) {

        that.setData({
          //下拉获取更多 使用concat进行数据的拼接，而不是用push，用push每次刷新都会请求新的页面
          cartGoods: that.data.cartGoods.concat(res.result),
          cartTotal: res.count,
          page: that.data.page + 1,
          totalPages: res.totalPages,
        });
      }
    });
  },

  //向服务请求支付参数
  requestPayParam(trade_sn, price) {
    let that = this;
    util.request(api.WXPayPrepayId, {
      trade_sn: trade_sn,
      openid: app.globalData.token,
      price: price
    }, 'GET').then(function (res) {
      console.log(res);
      if (res.state === 1) {
        wx.requestPayment({
          'timeStamp': res.timeStamp,
          'nonceStr': res.nonceStr,
          'package': res.package,
          'signType': res.signType,
          'paySign': res.paySign,
          'success': function (res) {
            wx.setStorageSync('trade_sn', trade_sn);

            //支付成功则进行模板消息的推送
            wx.request({
              url: api.sendTemplateMessage,
              data: {
                openid: app.globalData.token,
                trade_sn: trade_sn
              },
              method: 'GET',
              header: {
                "Content-type": "application/json",
              },
              success: function (res) {
                console.log(res);
              },
              fail: function (err) {
                console.log(err);
              },
              complete: function (res) {
                console.log(res);
              }
            })

            wx.redirectTo({
              url: '/pages/payResult/payResult?status=true',
            })
          },
          'fail': function (res) {
            wx.setStorageSync('trade_sn', trade_sn);
            wx.redirectTo({
              url: '/pages/payResult/payResult?status=false',
            })
          }
        })
      }
    });
  },
  startPay(e) {
    this.requestPayParam(e.currentTarget.dataset.tradesn, e.currentTarget.dataset.price);
  },
  toIndexPage() {
    wx.switchTab({
      url: '/pages/index/index',
    })
  }
})